﻿using System.Data.Entity;
using Autofac;
using TaskManager.DataAccess.Repositories;
using TaskManager.Domain.Repositories;

namespace TaskManager.DataAccess.Modules
{
    /// <summary>
    /// Encapsulates services provided by Data Access Layer
    /// </summary>
    public class DataAccessLayer : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            Database.SetInitializer(new DatabaseInitializer()); // Initialize database
           
            builder.RegisterType<TaskRepository>().As<ITaskRepository>().InstancePerLifetimeScope();
            builder.RegisterType<ProjectRepository>().As<IProjectRepository>().InstancePerLifetimeScope();
            builder.RegisterType<UserRepository>().As<IUserRepository>().InstancePerLifetimeScope();
            builder.RegisterType<ProjectLogWriter>().As<IProjectLogWriter>().InstancePerLifetimeScope();
            builder.RegisterType<TaskLogWriter>().As<ITaskLogWriter>().InstancePerLifetimeScope();

            builder.RegisterType<TaskManagerDbContext>()
                .As<IUnitOfWork>()
                .As<TaskManagerDbContext>()
                .InstancePerLifetimeScope()
                .OnActivated(arg =>
                // When EF de-serializes entity we need to resolve entity's dependencies.
                // The only way is subscribe on ObjectMaterialized event and ask Autofac to
                // resolve all dependencies.
                {
                    var ctx = arg.Context.Resolve<IComponentContext>();

                    TaskManagerDbContext dbContext = arg.Instance;

                    dbContext.ObjectMaterialized +=
                        (sender, objMaterializedEventArg) =>
                        {
                            object entity = objMaterializedEventArg.Entity;
                            ctx.InjectProperties(entity);
                        };
                });
        }
    }
}